<template>
  <div class="app-container">
    <el-form :model="menu" ref="menuForm" :rules="rules" label-position="top">
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="菜单类型" prop="type">
            <el-select style="width: 100%" v-model="menu.type" @change="setMenuType" placeholder="请选择">
              <el-option :value='0' label="目录"></el-option>
              <el-option :value='1' label="菜单"></el-option>
              <el-option :value='2' label="按钮"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="父级菜单" prop="parentId">
            <el-popover
              ref="popover"
              placement="bottom-end"
              width="380"
              v-model="treeShow"
              trigger="click">
              <div style="text-align: right; margin: 0">
                <el-tree
                  :data = "treeData"
                  node-key="id"
                  @node-click="setSelectedTreeNode"
                  ref="tree"
                  accordion
                  :props="defaultProps">
                   <span slot-scope ="{ node, data }">
                          <span>{{ generateTitle(node.label) }}</span>
                      </span>
                </el-tree>
              </div>
            </el-popover>
            <el-input disabled v-model="menu.parentName" v-popover:popover></el-input>
          </el-form-item>

        </el-col>
        <el-col :span="8">
          <el-form-item label="菜单名称" prop="name">
            <el-input  v-model="menu.name" auto-complete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col  :span="8">
          <el-form-item label="重定向路径" prop="redirect">
            <el-input  v-model="menu.redirect"  auto-complete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col v-show="!isButton" :span="8">
          <el-form-item label="菜单路径" prop="path" :class="{ 'is-required': !isButton }">
            <el-input  v-model="menu.path"  auto-complete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-show="isButton">
          <el-form-item label="权限" prop="perms" :class="{ 'is-required': isButton }">
            <el-input  v-model="menu.perms" auto-complete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-show="!isButton">
          <el-form-item label="组件地址" prop="component" :class="{ 'is-required': !isButton }">
            <el-input  v-model="menu.component" auto-complete="off"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8" v-show="!isButton">
          <el-form-item label="图标" prop="icon">
            <el-select style="width: 100%" v-model="menu.icon" placeholder="请选择">
              <el-option
                v-for="item in iconsMap"
                :key="item"
                :value="item">
                    <span style="float: left">
                      <svg-icon class-name="disabled" :icon-class="item" />
                    </span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item}}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="是否可用" prop="disabled">
            <el-switch  v-model="menu.disabled"> </el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="4" v-show="isMenu">
          <el-form-item label="是否缓存" prop="enabledCache">
            <el-switch  v-model="menu.enabledCache"> </el-switch>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row  >
      <el-col :span="5" :offset="6">
        <el-button type="primary" round @click="submitEdit">确定</el-button>
      </el-col>

      <el-col :span="5">
        <el-button type="danger" round @click="clearModel">清空</el-button>
      </el-col>
    </el-row>

  </div>
</template>

<script>
  import { saveOrUpdate,getMenuById } from '@/api/sys/menu/';
  import { generateTitle } from '@/utils/i18n'
  import icons from '@/utils/generateIconsView'
  export default {
    name:'editMenu',
    data() {
      var isValidate = (rule, value, callback) => {
        this.$nextTick(()=> {
          if(this.isButton){
            rule.required=false;

          }else{
            rule.required=true;

          }
        });

        if(!value){
          callback(new Error('必输项不能为空'))
        }else{
          callback();
        }

      }
      return {
        iconsMap: [],
        treeData:[{
          id: 0,
          name: "rootMenu",
          children:[],
          disabled: true,
          leaf:false
        }],
        treeShow:false,
        menu:{
          name:"",
          disabled: true,
          enabledCache: true,
        },
        isButton:false,
        isMenu: false,
        defaultProps: {
          children: 'children',
          label: 'name',
          isLeaf:'leaf',
          id:'id',
          disabled:function (data, node) {
            if(data.disabled){
              return false;
            }else{
              return true;
            }
          }
        },
        rules: {
          type: [
            {required: true, message: '请选择类型', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '请输入菜单名称', trigger: 'blur'}
          ],
          path: [
            {validator:isValidate,  trigger: 'blur'},
          ],
          perms: [
            {validator:isValidate, trigger: 'blur'},
          ],
          component: [
            {validator:isValidate, trigger: 'blur'},
          ]
        },
      }
    },
    mounted(){
    },
    created(){
        console.info('第一次执行，只执行一次')
    },
    activated(){
      console.log('每次都执行')
      this.init(this.$route.query.id);
      this.iconsMap = icons.state.iconsMap.map((i) => {

        return i.default.id.split('-')[1]
      })
    },
    deactivated(){
      console.log('离开的时候执行')
    },

    methods: {
      clearModel(){
        this.$refs.menuForm.resetFields();
      },
      searchMenuById(id){
        let that = this;
        getMenuById(id).then((result) =>{
          let {code,data,msg} = result.data;
          if(code == 0){
            that.menu = Object.assign({},data);
            /**
             * 根据父id设置选择的父节点
             */
            that.setSelectedTreeNode(null,that.$refs.tree.getNode(that.menu.parentId),null);
            /**
             * 设置菜单类型
             */
            that.setMenuType(that.menu.type);
          }else{
            that.$message.error(msg);
          }
        }).catch((error)=>{

        });


      },
      generateTitle,
      init(id){
        let that =this;
        /**
         * 直接从store中取出来菜单信息，追加到树节点中
         */
        if(that.treeData[0].children.length ==  0){
          this.$store.getters.addRouters.forEach((item)=>{
            this.$refs.tree.append(item,that.treeData[0])
          });
        }

        if(id){
          that.searchMenuById(id);
        }

      },
      setMenuType(value){
        this.$refs['menuForm'].clearValidate();
        this.$nextTick(()=> {
          if(value == '2'){
            this.isButton = true;
          }else if(value == '1'){
            this.isButton = false;
            this.isMenu = true;
          }else{
            this.isButton = false;
          }
          //this.menu.leaf=this.isButton;
        })



      },
      setSelectedTreeNode(data,node,tree){
        this.menu.parentId=node.data.id;
        this.menu.parentName=this.generateTitle(node.data.name);
        this.treeShow=false;
      },
      submitEdit(){
        let that = this;
        saveOrUpdate(this.menu).then(function (result) {
          let {code,msg} =result.data;
          if(code == 0){
            that.$message({
              type: 'success',
              message: msg
            });
          }else{
            that.$message.error('执行失败,'+msg);
          }
        }).catch(function (error) {
        });

      },
    }
  }

</script>
